//
//  EMConversationVC.swift
//  easeIM-swift
//
//  Created by yangjian on 2022/7/13.
//

import UIKit
import RxSwift
import HyphenateChat

class EMConversationVC: UIViewController {
    fileprivate let bag = DisposeBag()
    fileprivate let vcHelper = EMConversationVCHelper()
    
    
    let willReloadTableViewLock = NSObject()
    var willReloadTableView = false
    
    //单位:秒 将要刷新的时候,先做延迟,延迟过程中可能再次需要刷新,这样可将多次刷新合并为1次.做一轮缓冲
    let intervalBeforeReload = 1.0
    
    lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.delegate = self
        
        //设置cell
        tableView.register(EMConversationCell.self, forCellReuseIdentifier: "EMConversationCell")
        vcHelper.modelsSubject.bind(to: tableView.rx.items(cellIdentifier: "EMConversationCell", cellType: EMConversationCell.self),curriedArgument: { row,model,cell in
            cell.bindFromModel(cellModel: model)
        }).disposed(by: bag)
        
        
        //设置点击事件
//        tableView.rx.itemSelected.subscribe(onNext: {[unowned self] indexPath in
//            print(indexPath)
//        }).disposed(by: bag)
        
        
        
//        tableView.rx.itemSelected.subscribe(onNext: {[unowned self] indexPath in
//            print(indexPath)
//            self.tableView.deselectRow(at: indexPath, animated: true)
//            guard let conversation = self.vcHelper.models[indexPath.row].conversation else{
//                return
//            }
//            self.navigationController?.pushViewController(JJSingleChatVC.init(conversationid: conversation.conversationId, chatType: conversation.type), animated: true)
//        })
        
        
        
        tableView.rx.itemSelected.map {return $0}.subscribe(onNext: {[unowned self] indexPath in
            self.tableView.deselectRow(at: indexPath, animated: true)
            guard let conversation = self.vcHelper.models[indexPath.row].conversation else{
                return
            }
            self.navigationController?.pushViewController(JJSingleChatVC.init(conversationid: conversation.conversationId, chatType: conversation.type), animated: true)
        }).disposed(by: bag)
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configObservable()
        self.configUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.vcHelper.fetchConversations()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }

    
    
    
//    func configData(){
//        self.vcHelper.fetchConversations()
//    }
    
    func configObservable(){
//        RXEMObservableManager.share.chatObservable.rx_messagesDidReceive.subscribe(onNext:{[unowned self] messages in
//            objc_sync_enter(self.willReloadTableViewLock)
//            if self.willReloadTableView {
//                objc_sync_exit(self.willReloadTableViewLock)
//                print("等待刷新中...")
//                return
//            }
//            self.willReloadTableView = true
//            objc_sync_exit(self.willReloadTableViewLock)
//
//            DispatchQueue.main.asyncAfter(deadline: .now() + self.intervalBeforeReload) {
//                self.tableView.reloadData()
//                objc_sync_enter(self.willReloadTableViewLock)
//                self.willReloadTableView = false
//                objc_sync_exit(self.willReloadTableViewLock)
//            }
//        }).disposed(by: bag)
    }
    
    func configUI(){
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(app_safeAreaInsets.top + 44)
            make.left.equalTo(0)
            make.bottom.equalTo(0-(app_safeAreaInsets.bottom + 49))
            make.right.equalTo(0)
        }
        
        let buttonItem = UIBarButtonItem(title: "测", style: .plain, target: nil, action: nil)
        buttonItem.rx.tap.subscribe(onNext: {[unowned self] element in
            self.testAction(sender: (buttonItem))
        }).disposed(by: bag)
        self.navigationItem.leftBarButtonItem = buttonItem
        // Fallback on earlier versions

    }
    
    var test_setup:Bool = false
    var isJoined = false
    var roomID = "222110699028484"
}

extension EMConversationVC : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
}

extension EMConversationVC{
    func testAction(sender : UIBarButtonItem){
//        sender.menu = self.createMenu()
//        sender.showmenu
        
//        self.tableView.buildMenu(with: UIMenuBuilder())
        if !test_setup {
            self.setup()
            test_setup = true
        }
        self.run()
    }
    
    
    func setup(){
        RXEMObservableManager.share.chatroomObservable.rx_userDidJoin.subscribe(onNext: {[unowned self] chatroom , username in
            print("=====test=====\(username)-加入了-\(chatroom.chatroomId)")
        }).disposed(by: bag)
        RXEMObservableManager.share.chatroomObservable.rx_userDidLeave.subscribe(onNext: {[unowned self] chatroom , username in
            print("=====test=====\(username)-离开了-\(chatroom.chatroomId)")
        }).disposed(by: bag)
    }
    func run(){
        print("当前isJoined状态:\(self.isJoined)")
        if isJoined {
            EMClient.shared().roomManager?.leaveChatroom(roomID,completion: {[unowned self] error in
                if let error {
                    print("离开聊天室 失败,\(error.code)-\(error.errorDescription)")
                }else{
                    print("离开聊天室 成功")
                    self.isJoined = !self.isJoined
                }
            })
        }else{
            EMClient.shared().roomManager?.joinChatroom(roomID,completion: {[unowned self] room, error in
                if let error {
                    print("加入聊天室 失败,\(error.code)-\(error.errorDescription)")
                }else{
                    print("加入聊天室 成功")
                    self.isJoined = !self.isJoined
                }
            })
        }
    }
}
